package com.doge.service.wx.goods;

import com.alibaba.druid.util.StringUtils;
import com.doge.bean.base.BaseData;
import com.doge.bean.pojo.brand.Brand;
import com.doge.bean.pojo.brand.BrandExample;
import com.doge.bean.pojo.category.Category;
import com.doge.bean.pojo.category.CategoryExample;
import com.doge.bean.pojo.collect.CollectExample;
import com.doge.bean.pojo.comment.Comment;
import com.doge.bean.pojo.comment.CommentExample;
import com.doge.bean.pojo.footprint.Footprint;
import com.doge.bean.pojo.goods.*;
import com.doge.bean.pojo.issue.Issue;
import com.doge.bean.pojo.issue.IssueExample;
import com.doge.bean.pojo.searchhistory.SearchHistory;
import com.doge.bean.pojo.searchhistory.SearchHistoryExample;
import com.doge.bean.pojo.user.User;
import com.doge.bean.vo.wxgoods.*;
import com.doge.mapper.*;
import com.doge.util.auth.GetSubject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.nio.ch.FileKey;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @program: project2-wechat-mall
 * @description:
 * @author: 曾毅
 * @create: 2021-12-02 19:31
 **/
@Service
public class WxGoodsServiceImpl implements WxGoodsService {
    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    GoodsAttributeMapper goodsAttributeMapper;
    @Autowired
    BrandMapper brandMapper;
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    IssueMapper issueMapper;
    @Autowired
    GoodsProductMapper goodsProductMapper;
    @Autowired
    GoodsSpecificationMapper goodsSpecificationMapper;
    @Autowired
    CollectMapper collectMapper;
    @Autowired
    FootprintMapper footprintMapper;
    @Autowired
    SearchHistoryMapper searchHistoryMapper;

    @Override
    public long count() {
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.createCriteria().andDeletedEqualTo(false);
        long l = goodsMapper.countByExample(goodsExample);
        return l;
    }

    @Override
    public WxGoodsCategoryVO category(Integer id) {
        WxGoodsCategoryVO wxGoodsCategoryVO = new WxGoodsCategoryVO();
        Category category = categoryMapper.selectByPrimaryKey(id);
        if ("L1".equals(category.getLevel())) {
            //brotherCategory
            CategoryExample categoryExample = new CategoryExample();
            categoryExample.createCriteria().andPidEqualTo(id);
            List<Category> categoryList = categoryMapper.selectByExample(categoryExample);
            wxGoodsCategoryVO.setBrotherCategory(categoryList);
//            currentCategory
            Category cCategory = categoryMapper.selectCategoryByPidOne(id);
//            parentCategory
            Category pCategory = categoryMapper.selectByPrimaryKey(id);
            wxGoodsCategoryVO.setCurrentCategory(cCategory);
            wxGoodsCategoryVO.setParentCategory(pCategory);
            return wxGoodsCategoryVO;
        }
        //brotherCategory
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.createCriteria().andPidEqualTo(category.getPid());
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);
        //            currentCategory
        Category cCategory = categoryMapper.selectCategoryByIdOne(id);
        wxGoodsCategoryVO.setBrotherCategory(categoryList);
        //            parentCategory
        Category category1 = categoryMapper.selectByPrimaryKey(category.getPid());
        wxGoodsCategoryVO.setParentCategory(category1);
        wxGoodsCategoryVO.setCurrentCategory(category);
        return wxGoodsCategoryVO;
    }


    @Override
    public WxGoodsListVo list(Integer categoryId, Integer page, Integer limit, String keyword, String sort, String order) {
        PageHelper.startPage(page, limit);
        WxGoodsListVo wxGoodsListVo = new WxGoodsListVo();
        //此处数据暂时不用传，等老师弄清楚
        //        CategoryExample categoryExample = new CategoryExample();
//        categoryExample.createCriteria().andIdNotEqualTo(categoryId);
//        categoryExample.createCriteria().andLevelEqualTo("L2");
//        categoryExample.createCriteria().andDeletedEqualTo(false);
//        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);
        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria criteria = goodsExample.createCriteria();
        if (!StringUtils.isEmpty(keyword)) {
            criteria.andNameLike("%" + keyword + "%");
            if (GetSubject.getUser() != null) {
                SearchHistory searchHistory = new SearchHistory();
                searchHistory.setAddTime(new Date());
                searchHistory.setUpdateTime(new Date());
                searchHistory.setUserId(GetSubject.getUserId());

                SearchHistoryExample searchHistoryExample = new SearchHistoryExample();
                searchHistoryExample.createCriteria().andDeletedEqualTo(false).andUserIdEqualTo(GetSubject.getUserId()).andKeywordEqualTo(keyword);
                List<SearchHistory> searchHistories = searchHistoryMapper.selectByExample(searchHistoryExample);
                if (searchHistories.size()==0) {
                    searchHistory.setKeyword(keyword);
                    searchHistory.setFrom("微信");
                    searchHistoryMapper.insertSelective(searchHistory);
                }else {
                    SearchHistory searchHistory1 = searchHistories.get(0);
                    searchHistory1.setUpdateTime(new Date());
                    searchHistoryMapper.updateByPrimaryKeySelective(searchHistory1);
                }

            }
        }
        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            goodsExample.setOrderByClause(sort + " " + order);
        }
        if (categoryId != null && categoryId != 0) {
            criteria.andCategoryIdEqualTo(categoryId);
        }
        List<Goods> goodsList = goodsMapper.selectByExample(goodsExample);
        PageInfo pageInfo = new PageInfo(goodsList);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        wxGoodsListVo.setFilterCategoryList(null);
        wxGoodsListVo.setList(goodsList);
        wxGoodsListVo.setLimit(limit);
        wxGoodsListVo.setPage(page);
        wxGoodsListVo.setPages(pages);
        wxGoodsListVo.setTotal(total);
        return wxGoodsListVo;
    }

    @Override
    public BaseData related(Integer id) {
        Goods goods = goodsMapper.selectByPrimaryKey(id);
        PageHelper.startPage(1, 6);
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.createCriteria().andCategoryIdEqualTo(goods.getCategoryId());
        List<Goods> goodsList = goodsMapper.selectByExample(goodsExample);
        PageInfo pageInfo = new PageInfo();
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        BaseData baseData = new BaseData();
        baseData.setLimit(6);
        baseData.setPage(1);
        baseData.setTotal(total);
        baseData.setList(goodsList);
        baseData.setPages(pages);
        return baseData;
    }

    @Override
    public WxGoodsDetailVO detail(Integer id) {
        WxGoodsDetailVO wxGoodsDetailVO = new WxGoodsDetailVO();
        //根据id查询商品 ,info商品详情
        Goods goods = goodsMapper.selectByPrimaryKey(id);
        //attribute
        GoodsAttributeExample goodsAttributeExample = new GoodsAttributeExample();
        goodsAttributeExample.createCriteria().andGoodsIdEqualTo(id);
        List<GoodsAttribute> goodsAttributes = goodsAttributeMapper.selectByExample(goodsAttributeExample);

        //brand
        Brand brand = brandMapper.selectByPrimaryKey(goods.getBrandId());

        //comment
        GoodsDetailCommentVO goodsDetailCommentVO = new GoodsDetailCommentVO();
        CommentExample commentExample = new CommentExample();
        commentExample.createCriteria().andValueIdEqualTo(id);
        int count = (int) commentMapper.countByExample(commentExample);
        List<Comment> comments = commentMapper.selectByExample(commentExample);
        List<WxGoodsCommentVO> wxGoodsCommentVOS = new ArrayList<>();
        //TODO：商品页面显示的最大商品条数为2
        for (int i = 0; i < comments.size() && i < 3; i++) {
            Comment comment = comments.get(i);
            User user = userMapper.selectByPrimaryKey(comment.getUserId());
            wxGoodsCommentVOS.add(new WxGoodsCommentVO(comment.getAddTime(), comment.getAdminContent(),
                    user.getAvatar(), comment.getContent(), comment.getId(), user.getNickname(), comment.getPicUrls()));
        }
        goodsDetailCommentVO.setCount(count);
        goodsDetailCommentVO.setData(wxGoodsCommentVOS);

        //groupon团购不用写

        //issue
        IssueExample issueExample = new IssueExample();
        List<Issue> issues = issueMapper.selectByExample(issueExample);

        //productList

        GoodsProductExample goodsProductExample = new GoodsProductExample();
        goodsProductExample.createCriteria().andGoodsIdEqualTo(id);
        List<GoodsProduct> goodsProducts = goodsProductMapper.selectByExample(goodsProductExample);

        //share 就默认false
        //shareImage 为null

        //specificationList
        //过滤查询此商品对对应的所有规格
        List<SpecificationListVO> specificationListVOS = new ArrayList<>();
        GoodsSpecificationExample goodsSpecificationExample = new GoodsSpecificationExample();
        goodsSpecificationExample.setDistinct(true);
        goodsSpecificationExample.createCriteria().andGoodsIdEqualTo(id);
        List<GoodsSpecification> goodsSpecifications = goodsSpecificationMapper.selectByExample(goodsSpecificationExample);

        for (GoodsSpecification goodsSpecification : goodsSpecifications) {
            boolean flag = false;
            for (SpecificationListVO specificationListVO : specificationListVOS) {
                if (specificationListVO.getName().equals(goodsSpecification.getSpecification())) {
                    flag = true;
                    break;
                }

            }
            if (flag) continue;
            GoodsSpecificationExample goodsSpecificationExample1 = new GoodsSpecificationExample();
            GoodsSpecificationExample.Criteria criteria = goodsSpecificationExample1.createCriteria();
            criteria.andSpecificationEqualTo(goodsSpecification.getSpecification());
            criteria.andGoodsIdEqualTo(id);
            List<GoodsSpecification> goodsSpecifications1 = goodsSpecificationMapper.selectByExample(goodsSpecificationExample1);
            SpecificationListVO specificationListVO = new SpecificationListVO();
            specificationListVO.setName(goodsSpecification.getSpecification());
            specificationListVO.setValueList(goodsSpecifications1);
//            specificationListVO.setValueList(goodsSpecification);
            specificationListVOS.add(specificationListVO);
        }


        //userHasCollect
        CollectExample collectExample = null;
        if (GetSubject.getUser() != null) {
            User user = GetSubject.getUser();
            collectExample = new CollectExample();
            collectExample.createCriteria().andValueIdEqualTo(id).andUserIdEqualTo(user.getId());

        }
        int collectCount = (int) collectMapper.countByExample(collectExample);

        //赋值
        wxGoodsDetailVO.setAttribute(goodsAttributes);
        wxGoodsDetailVO.setBrand(brand);
        wxGoodsDetailVO.setComment(goodsDetailCommentVO);
        wxGoodsDetailVO.setGroupon(null);
        wxGoodsDetailVO.setInfo(goods);
        wxGoodsDetailVO.setIssue(issues);
        wxGoodsDetailVO.setProductList(goodsProducts);
        wxGoodsDetailVO.setShareImage(null);
        wxGoodsDetailVO.setSpecificationList(specificationListVOS);
        wxGoodsDetailVO.setUserHasCollect(collectCount);

        //用户浏览商品足迹
        if (GetSubject.getUser() != null) {
            Footprint footprint = new Footprint();
            footprint.setUserId(GetSubject.getUserId());
            footprint.setGoodsId(id);
            footprint.setAddTime(new Date());
            footprint.setUpdateTime(new Date());
            footprintMapper.insertSelective(footprint);
        }
        return wxGoodsDetailVO;
    }
}
